using MediatR;
using Microsoft.AspNetCore.Mvc;
using Traceability.API.APPLications.Commands.TraceabilityInfo;
using Traceability.API.APPLications.Commands.TraceabilityInfoshow;
using Traceability.API.Dtos;
using Traceability.ErrorCode;

namespace Traceability.API.Controllers
{
    /// <summary>
    /// 溯源信息控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TraceabilityInfoController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<TraceabilityInfoController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public TraceabilityInfoController(
            IMediator mediator,
            ILogger<TraceabilityInfoController> logger = null)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 添加溯源信息
        /// </summary>
        /// <param name="command">添加溯源信息命令</param>
        /// <returns>添加结果</returns>
        [HttpPost]
        public async Task<APIResult<int>> Add(AddTraceabilityInfoCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 更新溯源信息
        /// </summary>
        /// <param name="command">更新溯源信息命令</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<APIResult<bool>> Update(UpdateTraceabilityInfoCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 获取所有溯源信息（不带任何条件，仅分页）
        /// </summary>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>溯源信息列表</returns>
        [HttpGet]
        public async Task<APIResult<PagedResultDto<TraceabilityInfoDto>>> GetAll(int pageIndex = 1, int pageSize = 10)
        {
            var query = new GetAllTraceabilityInfoQuery
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            return await _mediator.Send(query);
        }

        /// <summary>
        /// 根据生产批次查询溯源信息
        /// </summary>
        /// <param name="productionBatch">生产批次</param>
        /// <returns>溯源信息</returns>
        [HttpGet("ByBatch/{productionBatch}")]
        public async Task<APIResult<TraceabilityInfoDto>> GetByBatch(string productionBatch)
        {
            _logger?.LogInformation("接收到根据生产批次查询请求: {ProductionBatch}", productionBatch);
            
            if (string.IsNullOrWhiteSpace(productionBatch))
            {
                return new APIResult<TraceabilityInfoDto>
                {
                    Code = APIEnum.操作失败,
                    Message = "生产批次不能为空"
                };
            }

            var query = new GetTraceabilityInfoByBatchQuery
            {
                ProductionBatch = productionBatch
            };
            return await _mediator.Send(query);
        }

        /// <summary>
        /// 物理删除溯源信息（永久删除，不可恢复）
        /// </summary>
        /// <param name="id">溯源信息ID</param>
        /// <param name="deleteBy">删除人</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<APIResult<bool>> Delete(int id, [FromQuery] string deleteBy)
        {
            _logger?.LogInformation($"单个删除请求接收: ID={id}, DeleteBy={deleteBy}");
            
            if (string.IsNullOrWhiteSpace(deleteBy))
            {
                return new APIResult<bool>
                {
                    Code = APIEnum.操作失败,
                    Message = "删除人不能为空",
                    Data = false
                };
            }

            var command = new DeleteTraceabilityInfoCommand
            {
                TraceabilityId = id,
                DeleteBy = deleteBy
            };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量物理删除溯源信息（永久删除，不可恢复）
        /// </summary>
        /// <param name="command">批量删除命令</param>
        /// <returns>删除结果</returns>
        [HttpPost("BatchDelete")]
        public async Task<APIResult<bool>> BatchDelete(BatchDeleteTraceabilityInfoCommand command)
        {
            _logger?.LogInformation($"批量删除请求接收: IDs数量={command.TraceabilityIds?.Count ?? 0}, DeleteBy={command.DeleteBy}");
            
            if (command.TraceabilityIds == null || command.TraceabilityIds.Count == 0)
            {
                return new APIResult<bool>
                {
                    Code = APIEnum.操作失败,
                    Message = "删除ID列表不能为空",
                    Data = false
                };
            }

            if (string.IsNullOrWhiteSpace(command.DeleteBy))
            {
                return new APIResult<bool>
                {
                    Code = APIEnum.操作失败,
                    Message = "删除人不能为空",
                    Data = false
                };
            }

            return await _mediator.Send(command);
        }

        /// <summary>
        /// 恢复已删除的溯源信息（注意：系统已改为物理删除，此功能不再适用）
        /// </summary>
        /// <param name="id">溯源信息ID</param>
        /// <param name="modifiedBy">修改人</param>
        /// <returns>恢复结果</returns>
        [HttpPut("{id}/restore")]
        public async Task<APIResult<bool>> Restore(int id, [FromQuery] string modifiedBy)
        {
            _logger?.LogInformation($"恢复请求接收: ID={id}, ModifiedBy={modifiedBy}");
            
            if (string.IsNullOrWhiteSpace(modifiedBy))
            {
                return new APIResult<bool>
                {
                    Code = APIEnum.操作失败,
                    Message = "修改人不能为空",
                    Data = false
                };
            }

            var command = new RestoreTraceabilityInfoCommand
            {
                TraceabilityId = id,
                ModifiedBy = modifiedBy
            };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 物理删除溯源信息（永久删除，不可恢复）
        /// </summary>
        /// <param name="id">溯源信息ID</param>
        /// <param name="deleteBy">删除人</param>
        /// <returns>删除结果</returns>
        [HttpDelete("Physical/{id}")]
        public async Task<APIResult<bool>> PhysicalDelete(int id, [FromQuery] string deleteBy)
        {
            _logger?.LogInformation("收到物理删除溯源信息请求，ID: {Id}, 删除人: {DeleteBy}", id, deleteBy);

            var command = new PhysicalDeleteTraceabilityInfoCommand
            {
                TraceabilityId = id,
                DeleteBy = deleteBy
            };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量物理删除溯源信息（永久删除，不可恢复）
        /// </summary>
        /// <param name="ids">溯源信息ID列表</param>
        /// <param name="deleteBy">删除人</param>
        /// <returns>删除结果</returns>
        [HttpDelete("Physical/Batch")]
        public async Task<APIResult<bool>> BatchPhysicalDelete([FromBody] List<int> ids, [FromQuery] string deleteBy)
        {
            _logger?.LogInformation("收到批量物理删除溯源信息请求，ID数量: {Count}, 删除人: {DeleteBy}", ids?.Count ?? 0, deleteBy);

            var command = new BatchPhysicalDeleteTraceabilityInfoCommand
            {
                TraceabilityIds = ids ?? new List<int>(),
                DeleteBy = deleteBy
            };
            return await _mediator.Send(command);
        }
    }
}